from playwright.sync_api import Playwright, sync_playwright
from typing import Dict, List, Tuple
import json


class MockTest:
    def __init__(self, playwright: Playwright):
        self.playwright = playwright
        self.browser = None
        self.page = None
        self.mock_data = {}

    def start_server(self, mock_data: Dict[str, List[Tuple[str, Dict[str, str], str]]]):
        self.mock_data = mock_data
        self.browser = self.playwright.chromium.launch(headless=True)
        self.page = self.browser.new_page()
        self.page.route("**/*", self.intercept_request)

    def stop_server(self):
        self.browser.close()

    def intercept_request(self, route, request):
        url = request.url
        if url in self.mock_data:
            status_code, headers, response = self.mock_data[url][0]
            del self.mock_data[url][0]
            if not self.mock_data[url]:
                del self.mock_data[url]
            route.fulfill(
                status=status_code,
                headers=headers,
                body=json.dumps(response))

    def verify_mock_data(self):
        assert not self.mock_data, 'Some expected requests were not made'
